package io.renren.modules.photography.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.FileUtil;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.photography.dao.PWorksDao;

import io.renren.modules.photography.entity.PWorksEntity;
import io.renren.modules.photography.service.PWorksService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service("pWorksService")
public class PWorksServiceImpl extends ServiceImpl<PWorksDao, PWorksEntity> implements PWorksService {


    /**
     * 根路径
     */
    @Value("${upload.serverPath}")
    private String serverPath;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PWorksEntity> page = this.page(
                new Query<PWorksEntity>().getPage(params),
                new QueryWrapper<PWorksEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R save(MultipartFile file, String path, String filesPath) throws IOException {
        //上传的文件名
        String fileName = file.getOriginalFilename();
        //判断后缀
        if (!fileName.contains(".")) {
            throw new IllegalArgumentException("缺少后缀名");
        }
        //md5
        String md5 = FileUtil.fileMd5(file.getInputStream());
        fileName = fileName.substring(fileName.lastIndexOf("."));
        //拼接路径
        String pathname = FileUtil.getPath() + md5 + fileName;
        String fullPath = filesPath + pathname;
        FileUtil.saveFile(file, fullPath);
        return R.ok().put("url","/files/"+path+pathname).put("allPath", serverPath + "/files/"+path+pathname);
    }

}